package com.advanced.controller;

import com.advanced.component.PratitionKeyComponent;
import com.advanced.mapper.ProductOrderMapper;
import com.advanced.model.ProductOrderDO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;
import java.util.UUID;

@RestController
@Slf4j
public class ShardingAdvancedUsageController {

    @Autowired(required = false)
    private ProductOrderMapper productOrderMapper;
    @Autowired
    private PratitionKeyComponent pratitionKeyComponent;


    /**
     * 免迁移扩容-分片键追加库表位的添加测试
     */
    @GetMapping("insertTest")
    public void insertTest(){
        Random random = new Random();
        for(int i=0; i<20;i++){
            ProductOrderDO productOrderDO = new ProductOrderDO();
            productOrderDO.setCreateTime(new Date());
            productOrderDO.setNickname("666i="+i);
            productOrderDO.setOutTradeNo(UUID.randomUUID().toString().substring(0,32));
            productOrderDO.setPayAmount(100.00);
            productOrderDO.setState("PAY");
            Long aLong = Long.valueOf(random.nextInt(50));
            productOrderDO.setUserId(aLong);

            // parationKey字段生成(分片键)
            // 生成方式，两组随机数相加，再通过murmurHash(),再转成62进制
            int random1 = random.nextInt(9999999) + 1000000;
            int random2 = random.nextInt(9999999) + 1000000;
            String partitionKey = pratitionKeyComponent.createPratition(random1 + "" + random2);
            productOrderDO.setPartitionKey(partitionKey);
            productOrderMapper.insert(productOrderDO);
        }
    }

    /**
     * 免迁移扩容-分片键追加库表位的查询测试
     */
    @GetMapping("selectTest")
    public Object selectTest(){
        ProductOrderDO productOrderDO = productOrderMapper.selectOne(new QueryWrapper<ProductOrderDO>().eq("partition_key", "1s6fLI1"));

        log.info(productOrderDO!=null ? productOrderDO.toString() : "无数据");

        return productOrderDO;
    }
}
